package com.net.model.base;

import androidx.lifecycle.MutableLiveData;

import com.drug.lib.util.DLog;
import com.net.model.bean.BaseResponse;
import com.net.model.exception.ApiException;
import com.net.model.exception.ExceptionEngine;

import io.reactivex.subscribers.ResourceSubscriber;

/**
 * 版权：星云飞救公司 版权所有
 *
 * @author zhouhequan
 * 版本：1.0
 * 创建日期：2021/10/25 or 9:46
 * 描述：http请求观察者
 */
public class CommonSubscriber<T> extends ResourceSubscriber<T> {
    private MutableLiveData<Resource<T>> liveData;

    public CommonSubscriber(MutableLiveData<Resource<T>> liveData) {
        this.liveData = liveData;

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (liveData != null) liveData.postValue(Resource.loading());
    }

    @Override
    public void onNext(T t) {
        if (liveData != null) liveData.postValue(Resource.response(t));
    }

    @Override
    public void onError(Throwable t) {
        t.printStackTrace();
        ApiException ex = ExceptionEngine.handleException(t);
        DLog.e("请求异常 code:" + ex.getCode() + "  message:" + ex.getMessage());
        if (liveData != null) liveData.postValue(Resource.failure(ex.getCode(), ex.getMessage()));
    }

    @Override
    public void onComplete() {

    }

    /**
     * 初始化错误的dto
     *
     * @param ex
     */
    private void setApiException(ApiException ex) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(ex.getCode());
        baseResponse.setMessage(ex.getMessage());
        DLog.e("请求异常 code:" + ex.getCode() + "  message:" + ex.getMessage());
        liveData.postValue(Resource.failure(baseResponse));
    }


}
